﻿using System.Web.Mvc;
using Sub.TaskPlanningDesk.Model.Services.Projects;
using Sub.TaskPlanningDesk.WebSite.ViewModels.Projects;
using Sub.TaskPlanningDesk.WebSite.Infrastructure;
using Sub.TaskPlanningDesk.WebSite.ViewModels.Tasks;
using Sub.TaskPlanningDesk.Model.Objects;

namespace Sub.TaskPlanningDesk.WebSite.Controllers
{
	public class TaskController : Controller
	{
		#region ctor

		private IProjectService _projectService;
		private ITaskService _taskService;

		public TaskController(IProjectService projectService, ITaskService taskService)
		{
			_projectService = projectService;
			_taskService = taskService;
		}

		#endregion

		[ActionName("Delete")]
		public ActionResult DeleteTask(int taskID, int projectID)
		{
			_taskService.Delete(taskID);
			return RedirectToAction(TheActions.Project.TaskList, TheControllers.Project, new { projectID = projectID });
		}

		[ActionName("Edit")]
		public ActionResult EditTask(int projectID, int? taskID = null)
		{
			Task task = new Task();
			bool isNew = true;
			var project = _projectService.ByID(projectID);

			if (taskID.HasValue)
			{
				task = _taskService.ByID(taskID.Value);
				isNew = false;
			}

			TaskModel model = new TaskModel(project, task, isNew);

			return View(TheViews.Task.Edit, model);
		}

		[HttpPost]
		[ActionName("Edit")]
		public ActionResult EditTask(TaskModel model)
		{
			Task task = model.GetTask();

			if (model.IsNew)
				_taskService.Create(task);
			else
			{
				task.ID = model.ID.Value;
				var inDB = _taskService.ByID(task.ID);
				//get data from user
				inDB.Description = model.Description;
				inDB.Overview = model.Overview;
				_taskService.Update(inDB);
			}

			return RedirectToAction(TheActions.Project.TaskList, TheControllers.Project, new { projectID = model.Project.ID });
		}

		[HttpGet]
		[ActionName("Done")]
		public ActionResult TaskDone(int taskID)
		{
			_taskService.Done(taskID);
			var task = _taskService.ByID(taskID);
			return RedirectToAction(TheActions.Project.TaskList, TheControllers.Project, new { projectID = task.ProjectID });
		}

		[HttpGet]
		[ActionName("UnDone")]
		public ActionResult TaskUnDone(int taskID)
		{
			_taskService.UnDone(taskID);
			var task = _taskService.ByID(taskID);
			return RedirectToAction(TheActions.Project.TaskList, TheControllers.Project, new { projectID = task.ProjectID });
		}

		[HttpGet]
		public ActionResult ChangeOrder(int projectID, string newIDs)
		{
			_taskService.ChangeOrder(projectID, newIDs);

			return Json(true, JsonRequestBehavior.AllowGet);
		}
	}
}
